/**
 * Filename: GAGameStatePostHandler.js
 * Author: Abid Hussain
 * Date Created: 07/06/2011
 */
exports.GAGameStatePostHandler = Core.Class.singleton({
	initialize: function(){
		this._baseUrl = null;
		this._udid = null;
		this._game = null;
		this._dbFiles = null;
		this._DbPath = null;
		this._lastModifiedTime = null;
		this._storage = new Storage.KeyValue();
		this._getParams();
	},
	/*
	 * Public method called by the user for gameStatePost
	 * */
	postGameState: function(delegate,files,level,experience){
		this._delegate = delegate;
		this._dbFiles = files;
		this._level = level;
		this._experience = experience;
		this._readGameState();
	},
	
	_getParams: function(){
		var responseObject = GAGameLoader.getResponseObject();
		if(responseObject != 'undefined' && responseObject != null){
			this._baseUrl = GAConfigurations.getURL();//responseObject.getGameServer();
		}
		this._udid = GAConfigurations.getUdid();
		this._game = GAConfigurations.getGameName();
		this._DbPath = GAConfigurations.getGameStateDBPath();
	},
	/*
	 * _readGameState: reads the game state stored in local memory of device
	 * */
	_readGameState: function(){
		var resources = [];
		var length = this._dbFiles.length;
		for(var i=0; i< length; i++){
			resources[i] = this._dbFiles[i];
		}
		GAPersistenceManager.loadResources(resources, this._myProgress.bind(this), this._myDoneLoading.bind(this),this._errorLoading.bind(this));
	},
	_myProgress: function(loaded, total) {
		GALogger.log("In Progress!!!");
		GALogger.log("Progress: " + loaded + " / " + total);
	},
	_myDoneLoading: function(){
		var filesData = [];
		var length = 0;
		try{
			length = this._dbFiles.length;
			for(var i=0; i< length; i++){
				var resourceName = this._dbFiles[i];
				var resource = GAPersistenceManager.getResource(resourceName);
				resource = JSON.stringify(resource);
				filesData[resourceName+'.json'] = {data: resource};
			} 
			var data = GACompressionManager.compressFiles(filesData);
			var webFectcher = new GAWebFetcher(this,30,0);
			var params = this._getPostParams();
			var url = this._baseUrl+"game_databases";
			console.log("Zuluuu::: Base URL to Post the Game is "+url);
			webFectcher.postData(url,params,data);
		}
		catch(exception){
			this._delegate.gameStatePostFailure('Error while loading resources = '+exception);
		}
	},
	_errorLoading: function(){
		this._delegate.gameStatePostFailure('Error while loading resources');
	},
	 _getPostParams: function(){
	    	var params = new Object();
			console.log("zaki:::::: RECORD ID IS "+GAConfigurations.getRecordID());	    	
	    	params.unique_id = GAConfigurations.getRecordID();
	    	params.XP = this._experience;
	    	
	    	/*params.type = 'userkey';
	    	params.userkey = GAConfigurations.getUserId();
	    	params.udid = GAConfigurations.getUdid();
	    	params.game = GAConfigurations.getGameCode();
	    	params.devicetype = GAConfigurations.getDeviceType();
	    	params.gameversion = GAConfigurations.getGameVersion();
	    	params.osType = GAConfigurations.getOsVersion();
	    	params.level = this._level;
	    	params.experience = this._experience;
	    	params.json = "1";*/
	    	return params; 
	    },
	
	webFetchSuccess: function(webFetcher, responseData){
		console.log("Zuluuu::: WebFetcher Success : "+responseData);
		try{
			var response = eval("(" + responseData + ")");
			//var serverResponse = response.ServerResponse;
			var status = response.status;
			//var statusCode = serverResponse['@status_code'];
			console.log("Zuluuu::: Status is "+status);
			if(status != true){
				this._delegate.gameStatePostFailure(status);
			}
			else{
				/*var updatedTime = serverResponse.GameStateLastUpdatedTime;
				updatedTime = this._dateFromUTC(updatedTime, "-");
				this._lastModifiedTime = Date.parse(updatedTime);
				this._saveLastModifiedTime(this._lastModifiedTime);
				* */
				this._delegate.gameStatePostSuccess();
			}
		}
		catch(exception){
			this._delegate.gameStatePostFailure(exception);
		}
		finally{
			if(webFetcher != null){
				webFetcher.destroy();
				webFetcher = null;
			}
		}
	},
	webFetchFailure: function(webFetcher, error){
		console.log("Zuluuu::: WebFetcher Failure : "+error);
		this._delegate.gameStatePostFailure(error);
		if(webFetcher != null){
			webFetcher.destroy();
			webFetcher = null;
		}
	},
	_dateFromUTC: function( dateAsString, ymdDelimiter ){
		 var pattern = new RegExp( "(\\d{4})" + ymdDelimiter + "(\\d{2})" + ymdDelimiter + "(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})" );
		 var parts = dateAsString.match( pattern );
		 return new Date(Date.UTC(parseInt( parts[1] ), parseInt( parts[2], 10 ) - 1, parseInt( parts[3], 10 ), parseInt( parts[4], 10 ), parseInt( parts[5], 10 ), parseInt( parts[6], 10 ),0));
	},
	_saveLastModifiedTime: function(value){
		this._storage.setItem(kGAGameState.kLastModifiedTime,value);
	},
	destroy: function(){
		this._delegate = null;
		this._level = null;
		this._experience = null;
		this._dbFiles = null;
		this._lastModifiedTime = null;
		this._storage = null;
		this._baseUrl = null;
		this._DbPath = null;
		this._udid = null;
		this._game = null;
	}
});